//
//  LogsViewController.m
//  iRMAP
//
//  Created by Ryan Enguero on 4/2/14.
//  Copyright (c) 2014 engueroryan. All rights reserved.
//

#import "LogsViewController.h"
#import "LogViewCellTableViewCell.h"
#import "ParserClass.h"
#import "DevicesCurrentTemperature-PGS.h"
#import "DevicesCurrentTemperature-Platinum.h"
#import "DevicesCurrentTemperature-CO2Incubator.h"
#import "DevicesCurrentTemperature-EGS-G2.h"
#import "DevicesCurrentTemperature-OFA_IFA_IFC_INA.h"

#define REFRESH_HEADER_HEIGHT 52.0f

@interface LogsViewController ()

@end
int test1 = 1;
int DropDownState1 = 0;
@implementation LogsViewController
@synthesize logsList;


- (id)initWithStyle:(UITableViewStyle)style {
    //  self = [super initWithStyle:style];
    self = [super init];
    if (self != nil) {
        [self setupStrings];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self != nil) {
        [self setupStrings];
    }
    return self;
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setupStrings];
        [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:0.0/255.0 green:30.0/255.0 blue:66.0/255.0 alpha:1.0], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:0.0/255.0 green:30.0/255.0 blue:66.0/255.0 alpha:1.0]];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [self.tblLogs reloadData];
    
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addPullToRefreshHeader];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255.0 green:30.0/255.0 blue:66.0/255.0 alpha:1.0];
    
    logsList = [NSMutableArray arrayWithObjects:@"Alarm Logs",@"Event Logs", nil];
    
    self.lblLogs.text = @"Alarm Logs";
    
    self.lblLogs.layer.cornerRadius = 6;
    self.btnCancelProp.layer.cornerRadius = 6;
    self.btnDoneProp.layer.cornerRadius = 6;
    
    [self.tabBarController.tabBar setHidden:YES];

    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnLogs:(id)sender {
    [self animationToolBar];
    
}

#pragma PickerSetup;

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [logsList count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return logsList[row];
}



#pragma Table Setup;

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{


    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if ([self.lblLogs.text isEqualToString:@"Alarm Logs"]) {
        
        return [[[ParserClass sharedItems] alarmLogs] count];
        
    }else if ([self.lblLogs.text isEqualToString:@"Event Logs"]){

        return [[[ParserClass sharedItems] eventLogs] count];
        
    }

    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *simpleTableIdentifier = @"SimpleTableItem";
    
    LogViewCellTableViewCell *cell = (LogViewCellTableViewCell*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LogViewCellTableViewCell" owner:simpleTableIdentifier options:nil];
        
        cell = [nib objectAtIndex:0];
    }
    
    if ([self.lblLogs.text isEqualToString:@"Alarm Logs"]) {
        
        Devices *devices = [[ParserClass sharedItems] alarmLogs][indexPath.row];
        
        if ([[devices deviceType] isEqualToString:@"ultf_gold"] || [[devices deviceType] isEqualToString:@"ultf_silver"] ) {
            
            DevicesCurrentTemperature_PGS *devicesGoldSilver = [[ParserClass sharedItems] alarmLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesGoldSilver occuranceTimeAlarm];
            cell.lblAlarmLog.text = [devicesGoldSilver alarmTextAlarm];
            
        }else if ([[devices deviceType] isEqualToString:@"ultf_platinum"]){
            
            DevicesCurrentTemperature_Platinum *devicesPlatinum = [[ParserClass sharedItems] alarmLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesPlatinum occuranceTimeAlarm];
            cell.lblAlarmLog.text = [devicesPlatinum alarmTextAlarm];

            
        }else if ([[devices deviceType] isEqualToString:@"co2_incubator"]){
            
            DevicesCurrentTemperature_CO2Incubator *devicesIncubator = [[ParserClass sharedItems] alarmLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesIncubator occuranceTimeAlarm];
            cell.lblAlarmLog.text = [devicesIncubator alarmTextAlarm];
            
        }else if ([[devices deviceType] isEqualToString:@"ecs-g2"]){
            
            DevicesCurrentTemperature_EGS_G2 *devicesEGSG2 = [[ParserClass sharedItems] alarmLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesEGSG2 occuranceTimeAlarm];
            cell.lblAlarmLog.text = [devicesEGSG2 alarmTextAlarm];
            
        }else if ([[devices deviceType] isEqualToString:@"ofa"] || [[devices deviceType] isEqualToString:@"ifa"] || [[devices deviceType] isEqualToString:@"ifc"] || [[devices deviceType] isEqualToString:@"ina"]){
            
            DevicesCurrentTemperature_OFA_IFA_IFC_INA *devicesOFAIFAIFCINA = [[ParserClass sharedItems] alarmLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesOFAIFAIFCINA occuranceTimeAlarm];
            cell.lblAlarmLog.text = [devicesOFAIFAIFCINA alarmTextAlarm];
            
        }

        
        
    }else if ([self.lblLogs.text isEqualToString:@"Event Logs"]){
        
        Devices *devices = [[ParserClass sharedItems] eventLogs][indexPath.row];
        
        if ([[devices deviceType] isEqualToString:@"ultf_gold"] || [[devices deviceType] isEqualToString:@"ultf_silver"] ) {
            
            DevicesCurrentTemperature_PGS *devicesGoldSilver = [[ParserClass sharedItems] eventLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesGoldSilver occuranceTimeEvent];
            cell.lblAlarmLog.text = [devicesGoldSilver eventCode];
            
            
        }else if ([[devices deviceType] isEqualToString:@"ultf_platinum"]){
            
            DevicesCurrentTemperature_Platinum *devicesPlatinum = [[ParserClass sharedItems] eventLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesPlatinum occuranceTimeEvent];
            cell.lblAlarmLog.text = [devicesPlatinum eventCode];
            
        }else if ([[devices deviceType] isEqualToString:@"co2_incubator"]){
            
            DevicesCurrentTemperature_CO2Incubator *devicesIncubator = [[ParserClass sharedItems] eventLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesIncubator occuranceTimeEvent];
            cell.lblAlarmLog.text = [devicesIncubator eventCode];
            
        }else if ([[devices deviceType] isEqualToString:@"ecs-g2"]){
            
            DevicesCurrentTemperature_EGS_G2 *devicesEGSG2 = [[ParserClass sharedItems] eventLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesEGSG2 occuranceTimeEvent];
            cell.lblAlarmLog.text = [devicesEGSG2 eventCode];
            
            
        }else if ([[devices deviceType] isEqualToString:@"ofa"] || [[devices deviceType] isEqualToString:@"ifa"] || [[devices deviceType] isEqualToString:@"ifc"] || [[devices deviceType] isEqualToString:@"ina"]){
            
            DevicesCurrentTemperature_OFA_IFA_IFC_INA *devicesOFAIFAIFCINA = [[ParserClass sharedItems] eventLogs][indexPath.row];
            
            cell.lblLocalTime.text = [devicesOFAIFAIFCINA occuranceTimeEvent];
            cell.lblAlarmLog.text = [devicesOFAIFAIFCINA eventCode];
            
        }

        
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *simpleTableIdentifier = @"SimpleTableItem";
    
    LogViewCellTableViewCell *cellHeader = (LogViewCellTableViewCell*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    
    
    if (cellHeader == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LogViewCellTableViewCell" owner:simpleTableIdentifier options:nil];
        
        cellHeader = [nib objectAtIndex:0];
    }
    
    [cellHeader.lblLocalTime setText:@"LOCAL TIME"];
    //[cellHeader.lblRemoteTime setText:@"REMOTE TIME"];
    [cellHeader.lblAlarmLog setText:@"ALARM LOG"];
    [cellHeader.lblAlarmLog setTextAlignment:NSTextAlignmentCenter];
    
    return cellHeader;
}



#pragma ButtonsAction;


- (IBAction)btnCancel:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.datePicker setFrame:CGRectMake(0, 568, 320, 221)];
        [self.datePicker setAlpha:0.0];
    }completion:^(BOOL finished){
        [self.datePicker removeFromSuperview];
        test1 = 1;
    }];
}

- (IBAction)btnDone:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.datePicker setFrame:CGRectMake(0, 568, 320, 221)];
        [self.datePicker setAlpha:0.0];
    }completion:^(BOOL finished){
        [self.datePicker removeFromSuperview];
        
        NSString *logPick = [self pickerView:self.LogPicker titleForRow:[self.LogPicker selectedRowInComponent:0] forComponent:0 ];
        
            self.lblLogs.text = logPick;
        [self.tblLogs reloadData];
        test1 = 1;
    }];
    
}


-(void)animationToolBar{
    if (test1 == 1) {
        
        [self.datePicker setFrame:CGRectMake(0, 568, 320, 221)];
        [self.view addSubview:self.datePicker];
        [self.datePicker setAlpha:0.0];
        [UIView animateWithDuration:0.5 animations:^{
            
            [self.datePicker setFrame:CGRectMake(0, 300, 320, 221)];
            [self.datePicker setAlpha:1.0];
        }completion:^(BOOL finished){
            
            
            test1 = 2;
        }];
        
        //NSLog(@"test %i",test);
        
    }else if (test1 == 2){
        
        [self.datePicker setFrame:CGRectMake(0, 300, 320, 221)];
        [self.datePicker setAlpha:1.0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            [self.datePicker setFrame:CGRectMake(0, 568, 320, 221)];
            [self.datePicker setAlpha:0.0];
        }completion:^(BOOL finished){
            [self.datePicker removeFromSuperview];
            test1 = 1;
        }];
        
        //NSLog(@"test %i",test);
    }
    
}


#pragma mark - Refresh Method

- (void)setupStrings{
    
    textPull = @"Pull down to refresh...";
    textRelease = @"Release to refresh...";
    textLoading = @"Loading...";
}

- (void)addPullToRefreshHeader {
    refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
    refreshHeaderView.backgroundColor = [UIColor clearColor];
    
    refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, REFRESH_HEADER_HEIGHT)];
    refreshLabel.backgroundColor = [UIColor clearColor];
    refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
    refreshLabel.textAlignment = NSTextAlignmentCenter;
    
    refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
    refreshArrow.frame = CGRectMake(floorf((REFRESH_HEADER_HEIGHT - 27) / 2),
                                    (floorf(REFRESH_HEADER_HEIGHT - 44) / 2),
                                    27, 44);
    
    refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    refreshSpinner.frame = CGRectMake(floorf(floorf(REFRESH_HEADER_HEIGHT - 20) / 2), floorf((REFRESH_HEADER_HEIGHT - 20) / 2), 20, 20);
    refreshSpinner.hidesWhenStopped = YES;
    
    [refreshHeaderView addSubview:refreshLabel];
    [refreshHeaderView addSubview:refreshArrow];
    [refreshHeaderView addSubview:refreshSpinner];
    [self setupStrings];
    [self.tblLogs addSubview:refreshHeaderView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (isLoading) return;
    isDragging = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (isLoading) {
        // Update the content inset, good for section headers
        if (scrollView.contentOffset.y > 0)
            self.tblLogs.contentInset = UIEdgeInsetsZero;
        else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
            self.tblLogs.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (isDragging && scrollView.contentOffset.y < 0) {
        // Update the arrow direction and label
        [UIView animateWithDuration:0.25 animations:^{
            if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
                // User is scrolling above the header
                refreshLabel.text = self.textRelease;
                [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
            } else {
                // User is scrolling somewhere within the header
                refreshLabel.text = self.textPull;
                [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
            }
        }];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (isLoading) return;
    isDragging = NO;
    if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT) {
        // Released above the header
        [self startLoading];
    }
}

- (void)startLoading {
    isLoading = YES;
    
    // Show the header
    [UIView animateWithDuration:0.3 animations:^{
        self.tblLogs.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
        refreshLabel.text = self.textLoading;
        refreshArrow.hidden = YES;
        [refreshSpinner startAnimating];
    }];
    
    // Refresh action!
    [self refresh];
    [self refreshView];
}

- (void)stopLoading {
    isLoading = NO;
    
    // Hide the header
    [UIView animateWithDuration:0.3 animations:^{
        self.tblLogs.contentInset = UIEdgeInsetsZero;
        [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    }
                     completion:^(BOOL finished) {
                         [self performSelector:@selector(stopLoadingComplete)];
                     }];
}

- (void)stopLoadingComplete {
    // Reset the header
    refreshLabel.text = self.textPull;
    refreshArrow.hidden = NO;
    [refreshSpinner stopAnimating];
}

- (void)refresh {
    // This is just a demo. Override this method with your custom reload action.
    // Don't forget to call stopLoading at the end.
    
    //  dispatch_async(dispatch_get_main_queue(), ^{
    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:2.0];
    // });
    
}

- (void)dealloc {
    //    [refreshHeaderView release];
    //    [refreshLabel release];
    //    [refreshArrow release];
    //    [refreshSpinner release];
    //    [textPull release];
    //    [textRelease release];
    //    [textLoading release];
    //   [super dealloc];
}


//-(void)setMeasurementsData:(NSString *)measurementData{
//
//    deviceType = measurementData;
//}


- (void)refreshView {
    //dispatch_async(dispatch_get_main_queue(), ^{
    [self performSelector:@selector(addItem) withObject:nil afterDelay:1.0];
    //});
    
}

- (void)addItem {
    // Add a new time
    //    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    //    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    //    NSString *now = [dateFormatter stringFromDate:[NSDate date]];
    //    [items insertObject:[NSString stringWithFormat:@"%@", now] atIndex:0];
    
    // Devices *devices = [[ParserClass sharedItems] deviceDetails][self.pathIndex.row];
//    User *user = [[ParserClass sharedItems] userdetails][0];
//    ParserClass *parser = [ParserClass sharedItems];
//    
//    NSDictionary *json = [[PostClass sharedItems] getSensorLog:[user sessionID] andDomainID:[[ParserClass sharedItems] domainID] andDeviceID:[parser freezerID]];
//    
//    
//    if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
//        
//        [parser sensorLogs:json];
//    }
//    
//    
//    
//    NSLog(@"Refresh sensor log count = %i",[[[ParserClass sharedItems] sensorLogs] count]);
    [self.tblLogs reloadData];
    
    [self stopLoading];
}



@end
